package com.time.workshop.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.time.workshop.API;
import com.time.workshop.BaseConstant;
import com.time.workshop.R;
import com.time.workshop.SuperActivity;
import com.time.workshop.bean.BaseResponse;
import com.time.workshop.bean.UserInfo;
import com.time.workshop.injector.Injector;
import com.time.workshop.injector.V;
import com.time.workshop.utils.CommonUtils;
import com.time.workshop.utils.NewToast;
import com.time.workshop.utils.PreferenceUtil;
/**
 * 注册
 * @author wangfeng
 *
 */
public class RegisterActivity extends SuperActivity implements OnClickListener{

	public View rootView;
	@V
	private ImageView img_fragment_title;
	@V
	private TextView txt_fragment_title,tv_reg_obtain;
	@V
	private Button btn_fragment_left,btn_reg;
	@V
	private EditText et_reg_phone,et_reg_code,et_reg_password;

	private String phone,code,psw;
	private String smsstr = "";
	private TimeCount mTiemTimeCount;
	/** 返回数据总体的实体类 */
	private class Response extends BaseResponse<UserInfo>{};
	private Response mUserInfo;
	@Override
	protected void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		baseView.setTitleView(this, R.layout.base_view_titleleft,
				R.layout.base_view_titlecenter_with_logo,
				0,
				R.layout.activity_reg);
		rootView = baseView.getTitleView();
		setContentView(rootView);
		init();
	}

	private void init(){
		Injector.getInstance().inject(this);
		img_fragment_title.setVisibility(View.GONE);
		txt_fragment_title.setVisibility(View.VISIBLE);
		txt_fragment_title.setText(getResources().getString(R.string.rsg));
		txt_fragment_title.setTextColor(getResources().getColor(R.color.black));
		btn_fragment_left.setOnClickListener(this);
		btn_reg.setOnClickListener(this);
		tv_reg_obtain.setOnClickListener(this);
		mTiemTimeCount = new TimeCount(60000, 1000);
	}

	//计时重发
	private class TimeCount extends CountDownTimer {

		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);
		}

		@Override
		public void onTick(long millisUntilFinished) {
			tv_reg_obtain.setClickable(false);
			tv_reg_obtain.setText(millisUntilFinished / 1000 + "秒");
		}

		@Override
		public void onFinish() {
			tv_reg_obtain.setText(getResources().getString(R.string.tv_obtain));
			tv_reg_obtain.setClickable(true); 
		}
	}

	@Override
	public void onClick(View view) {
		phone = et_reg_phone.getText().toString().trim();
		code = et_reg_code.getText().toString().trim();
		psw = et_reg_password.getText().toString().trim();
		switch (view.getId()) {
		case R.id.btn_fragment_left:
			CommonUtils.hide(context);
			back();
			break;
		case R.id.btn_reg:
			if (!CommonUtils.isMobile(phone)) {
				NewToast.makeText(this, getResources().getString(R.string.toast_phone));
				return;
			}
			if ("".equals(CommonUtils.isnull(code))) {
				NewToast.makeText(this, getResources().getString(R.string.toast_code));
				return;
			}
			if ("".equals(CommonUtils.isnull(psw))) {
				NewToast.makeText(this, getResources().getString(R.string.toast_psw));
				return;
			}
			reqReg();
			break;

		case R.id.tv_reg_obtain:
			if (!CommonUtils.isMobile(phone)) {
				NewToast.makeText(this, getResources().getString(R.string.toast_phone));
				return;
			}
			mTiemTimeCount.start();
			reqSMS();
			break;

		default:
			break;
		}
		super.onClick(view);
	}
	
	private void reqSMS(){
		HttpUtils http = new HttpUtils();
		if (!CommonUtils.isNetworkConnected(getApplicationContext())) {
			NewToast.makeText(getApplicationContext(), getResources().getString(R.string.M000));
			return;
		}
		http.send(HttpMethod.GET, API.sms+"?username="+phone+"&type=1", new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				// TODO Auto-generated method stub
				try {
					JSONObject object = new JSONObject(responseInfo.result);
					smsstr = object.getString("result");
					NewToast.makeText(getApplicationContext(), object.getString("message"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				System.out.println(msg);
			}
		});
	}
	
	private void reqReg(){
		RequestParams param = new RequestParams();
		param.addBodyParameter("username", phone);
		param.addBodyParameter("password", psw);
		param.addBodyParameter("sms_token", smsstr);
		param.addBodyParameter("validate", code);
		HttpUtils http = new HttpUtils();
		http.send(HttpMethod.POST, API.reg, param, new RequestCallBack<String>() {

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				Log.d("onSuccess==", responseInfo+"");
				try {
					Gson gson = new Gson();
					mUserInfo = gson.fromJson(responseInfo.result, Response.class);
					NewToast.makeText(getApplicationContext(), mUserInfo.getMessage());
					if (mUserInfo.isSuccess()) {
						CommonUtils.hide(context);
						tv_reg_obtain.setText(getResources().getString(R.string.tv_obtain));
						tv_reg_obtain.setClickable(true); 
						//保存用户名和登录返回的Token
						PreferenceUtil.putString(RegisterActivity.this, BaseConstant.PREF_USERNAME_STRING, mUserInfo.getResult().getUSERNAME());
						PreferenceUtil.putString(RegisterActivity.this, BaseConstant.PREF_TOKE_STRING, mUserInfo.getResult().getTOKEN()+"");
						PreferenceUtil.putString(RegisterActivity.this, BaseConstant.PREF_PASSWORD_STRING, psw+"");
						Intent in = new Intent(RegisterActivity.this , MainActivity.class);
						startActivity(in, true);
						LoginActivity.loginActivity.finish();
						finish();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException error, String msg) {
				Log.d("onFailure==", msg+"");
				NewToast.makeText(getApplicationContext(), "fail"+msg);
			}
		});
	}



}
